import math
import uuid

from django.forms import model_to_dict
from elasticsearch import Elasticsearch

from goodsApp.goodsModel.models import Goods
from searchApp.configuration.esconfig import ElasticSearchConfig
from utils.spider.spider_jindon import fetch_data_from_jindon

# 去 elasticesearch
class SearchService:
    def search(self,keyword,current,size):
        num = Goods.objects.filter(description__icontains=keyword).count()
        if num==0:
            result=self.__fetch_data(keyword)
            self.saveGoods(result)
        start = int(current)*int(size)
        end = start+int(size)
        data = Goods.objects.filter(description__icontains=keyword)
        total_pages = math.ceil( len(data)/10 )
        goodsList = []
        for ele in data[start:end]:
            goodsList.append(model_to_dict(ele))
        return {'goodsList':goodsList,'total_page':total_pages}

    def saveGoods(self,result):
        goodsList = []
        protocol = 'https:'
        for goods in result:
            # source = goods['_source']
            title = goods['title']
            desc = goods['desc']
            goodsInfo = Goods(id=None,
                              price=goods['price'],
                              title= "额，标题飞走了" if title==None or len(title)==0 else title,
                              href=goods['href'],
                              storage=100,
                              img=protocol+goods['img'],
                              description="糟糕，没有描述" if desc==None or len(desc)==0 else desc,
                              categoryId=None)
            goodsList.append(goodsInfo)
        Goods.objects.bulk_create(goodsList)

    def __fetch_data(self,keyword):
        '''
            从京东抓取数据
            并且添加到 elasticsearch中
        '''
        return fetch_data_from_jindon(keyword,50)

